%% The MIT License
%% 
%% Paralog is licensed under the MIT License.
%% 
%% Copyright (c) 2008 Robert Ahrens <mindangels@yahoo.com>
%% 
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), to deal
%% in the Software without restriction, including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%% copies of the Software, and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%% 
%% The above copyright notice and this permission notice shall be included in
%% all copies or substantial portions of the Software.
%% 
%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%% THE SOFTWARE.
%% 

%% @author Robert Ahrens <mindangels@yahoo.com>
-module(pl_interpreter, [DB, Modules]).

-export([
         call/2,
         db/0,
         load/1,
         load_list/1,
         modules/0,
         shutdown/0
        ]).


db() ->
    DB.


modules() ->
    Modules.


load(Mod) when is_atom(Mod) ->
    case lists:member(Mod, Modules) of
        true -> 
            throw({error, already_loaded});
        false ->
            DB:load(Mod:kb()),
            new(DB, [Mod|Modules])
    end.


load_list(ModList) when is_list(ModList) ->
    NewMods = [M || M <- ModList, not(lists:member(M, Modules))],
    NewDB = lists:foldl(
              fun (M, ThisDB) ->
                      ThisDB:load(M:kb())
              end,
              DB,
              NewMods
             ),
    new(NewDB, NewMods ++ Modules).


call(Rule, Args) when is_atom(Rule) andalso is_list(Args) ->
    case pl_run:call_rule(Rule, Args, [], DB) of
        {ok, FinalVal, Bindings, _DB2} ->
            {ok, FinalVal, Bindings};
        fail ->
            fail
    end.
            

shutdown() ->
    DB:stop().
  
